<template>
  <div class="combined-module">
    <div class="cesiumContainerBox">
      <div class="layer"></div>
      <div id="cesiumContainer" style="height: 83vh;width: 100%;"></div>
    </div>

    <!-- 切换按钮 -->
    <div class="module-switch">
      <button class="switch-btn" @click="toggleRedPolygons">{{ redPolygonsVisible ? '隐藏' : '显示' }}</button>
      <button :class="['switch-btn', { 'active': currentModule === 'module1' }]"
        @click="switchModule('module1')">空域需求审批</button>
      <button :class="['switch-btn', { 'active': currentModule === 'module2' }]"
        @click="switchModule('module2')">需求管理匹配</button>
      <button :class="['switch-btn', { 'active': currentModule === 'module6' }]"
        @click="switchModule('module6')">运行实时管控</button>
      <!-- <button :class="['switch-btn', { 'active': currentModule === 'module3' }]"
        @click="switchModule('module3')">空域方案查看</button> -->
    </div>

    <!-- 批量审批弹窗 -->
    <CustomSubmitDialogAdd :visible.sync="globalDialogVisible" width="1200px" height="800px"
      @update:visible="globalDialogVisible = $event" @refresh-data="refreshModule1Data" />


    <!-- 添加 viewerReady 判断 -->
    <template v-if="viewerReady">
      <Module1Content v-if="currentModule === 'module1'" :cesiumViewer="viewer" @open-dialog="handleGlobalDialogOpen"
        @switch-to-module3="handleSwitchToModule3" />
      <Module2Content v-if="currentModule === 'module2'" :cesiumViewer="viewer" />
      <Module3Content v-if="currentModule === 'module3'" :cesiumViewer="viewer"
        @back-to-module1="handleBackToModule1" />
      <Module6Content v-if="currentModule === 'module6'" :cesiumViewer="viewer" @update-red-polygons="handleRedPolygons"
        @module6-finished="onModule6Finished" @store-module6-base-entities="handleStoreModule6Final" />
    </template>
  </div>
</template>

<script>
import Module1Content from '@/components/Module1AirspaceNeed.vue'
import Module2Content from '@/components/Module2PlanningRelease.vue'
import Module3Content from '@/components/Module2PlanningScheme.vue'
import Module6Content from '@/components/Module6Manage.vue'
import CustomSubmitDialogAdd from '@/components/CustomDialogModule2Add.vue';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE6;

const baseWebsocketApi = process.env.VUE_APP_WEBSOCKET

export default {
  name: 'CombinedModule',
  components: {
    Module1Content,
    Module2Content,
    Module3Content,
    Module6Content,
    CustomSubmitDialogAdd
  },
  data() {
    return {
      currentModule: 'module6',
      viewer: null,
      viewer1: null,
      viewerReady: false,  // 添加标志位
      redPolygons: [], // 存储禁飞区-红色多边形柱体
      hasDrawnRedPolygons: true,  //是否绘制过禁飞区标识
      waitingForClear: false,  //是否得到module6切换航路完毕信号
      globalDialogVisible: false,
      redPolygonsVisible: true, // 禁飞区显示状态
      module6FinalEntities: [], // 暂存 Module6 销毁时的最终实体（Module1 Module2 的初始数据来源）
    }
  },
  async mounted() {
    await this.initializeCesium()
    this.viewerReady = true  // 初始化完成后设置标志位
  },
  methods: {
    switchModule(moduleName) {
      // 1. 记录切换前的模块（判断是否从 Module3 来）
      const oldModule = this.currentModule;

      // 2. 清除当前实体（Module3 切换时需清除其绘制的内容）
      this.viewer.entities.removeAll();

      // 3. 执行模块切换
      this.currentModule = moduleName;

      // 4. 精准判断：仅从 Module3 切换到 Module1/Module2 时恢复
      const needRestore =
        oldModule === 'module3' &&
        (moduleName === 'module1' || moduleName === 'module2');

      if (needRestore && this.module6FinalEntities.length > 0) {
        this.restoreModule6Entities();
      }
    },
    // 处理 Module1 → Module3 的切换
    handleSwitchToModule3() {
      // 清除当前实体（Module1的内容）
      this.viewer.entities.removeAll();
      // 仅切换模块，不做任何数据清理（Module3 渲染时会自己绘制，销毁时会自己清理）
      this.currentModule = 'module3';
    },
    // 处理 Module3 → Module1 的切换（核心：恢复 Module6 的基准数据）
    handleBackToModule1() {
      // 1. 清除当前实体（Module3的内容）
      this.viewer.entities.removeAll();

      // 2. 切换到Module1
      this.currentModule = 'module1';

      // 3. 直接恢复Module6的基准数据
      if (this.module6FinalEntities.length > 0) {
        this.restoreModule6Entities();
      }
    },

    // 核心方法：直接在Cesium中恢复Module6的基准实体
    restoreModule6Entities() {
      // 遍历暂存的实体，重新添加到viewer
      this.module6FinalEntities.forEach(entity => {
        // 检查实体是否已存在，避免重复添加
        if (!this.viewer.entities.contains(entity)) {
          this.viewer.entities.add(entity);
        }
      });
      console.log(`已从Module6恢复${this.module6FinalEntities.length}个实体`);
    },
    // 接收 Module6 传递的基准数据并暂存
    handleStoreModule6Final(entities) {
      this.module6FinalEntities = entities;
      console.log('CombinedModule 已暂存 Module6 基准数据，共', this.module6FinalEntities.length, '个实体');
    },

    async initializeCesium() {
      try {
        // this.viewer = new Xmap.Viewer('cesiumContainer').viewer;
        this.viewer1 = new Xmap.Viewer('cesiumContainer', {
          infoBox: true, // ✅ 放在这里
          selectionIndicator: true,
        });
        this.viewer = this.viewer1.viewer
        window._viewer = this.viewer; // 👈 暴露给控制台
        window._xmap = this.viewer1
        // Xmap.AirspaceManage.HierarchicalGrid.createImageryProvider('xyz',
        //   {
        //     url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
        //   })
        this.viewer.imageryLayers.addImageryProvider(
          new Cesium.OpenStreetMapImageryProvider({
            // url: `http://192.168.0.135:8001/rsimageofhigh`,
            url: process.env.VUE_APP_MAP,
            fileExtension: 'png',
            maximumLevel: 19,
          })
        )
        // // 加载3dtiles模型数据
        // Xmap.AirspaceManage.HierarchicalGrid.load3dtiles('http://192.168.0.135:9027/prod-api/static/3dtiles3/tileset.json')
        // 全国高程数据
        Xmap.AirspaceManage.HierarchicalGrid.loadDEM(process.env.VUE_APP_HEIGHT_MAP, true)
        // 珠海倾斜摄影
        Xmap.AirspaceManage.HierarchicalGrid.load3dtiles(['http://192.168.0.135:8005/3dtiles/zhuhaitongji3dtile/tileset.json'])
        // // 横琴白膜
        // Xmap.AirspaceManage.HierarchicalGrid.load3dtiles(['http://192.168.0.135:8005/3dtiles/zhuhai3dtile/tileset.json'])
        // // 骆岗白膜
        // Xmap.AirspaceManage.HierarchicalGrid.load3dtiles(['http://192.168.0.135:8005/3dtiles/luogang3dtile/tileset.json'])
        // // 镇江白膜
        // Xmap.AirspaceManage.HierarchicalGrid.load3dtiles(['http://192.168.0.135:8005/3dtiles/zhenjiang3dtile/tileset.json'])


        this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [
          Cesium.CameraEventType.WHEEL
        ];
        // console.log("Cesium.CameraEventType",Cesium.CameraEventType )
        this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [
          Cesium.CameraEventType.MIDDLE_DRAG // 鼠标中键按下事件
        ];
        // 设置初始相机视图
        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(113.5405629, 22.1247559, 17000),
        });
        console.log('Cesium version', Cesium.VERSION);
      } catch (error) {
        console.error('Cesium initialization failed:', error);
      }
    },
    handleRedPolygons(entities) {
      this.redPolygons = entities;
      console.log("从模块6拿到的禁飞区数据", this.redPolygons)

      // 👇 初始状态统一隐藏实体
      this.redPolygons.forEach((entity) => {
        entity.show = false;
      });

      this.redPolygonsVisible = false; // 设置按钮初始状态为“显示”
      this.hasDrawnRedPolygons = true;
    },
    clearRedPolygons() {
      if (this.viewer && this.redPolygons.length > 0) {
        this.redPolygons.forEach((entity) => {
          this.viewer.entities.remove(entity);
        });
      }
    },
    showRedPolygons() {
      if (this.viewer && this.redPolygons.length > 0) {
        this.redPolygons.forEach((entity) => {
          this.viewer.entities.add(entity);
        });
      }
    },
    onModule6Finished() {
      if (this.waitingForClear) {
        console.log('Module6 已清除完成，准备清除红色区域');
        this.clearRedPolygons();
        this.waitingForClear = false;
      }
    },
    handleGlobalDialogOpen() {
      this.globalDialogVisible = true;
    },
    refreshModule1Data() {
      // 如果你要通知 Module1 更新数据，可以：
      this.$refs.module1Ref?.fetchTableData?.();
    },
    toggleRedPolygons() {
      this.redPolygonsVisible = !this.redPolygonsVisible;

      if (this.redPolygons.length > 0) {
        this.redPolygons.forEach((entity) => {
          entity.show = this.redPolygonsVisible;
        });
      }
    }
  }
}
</script>

<style scoped>
.cesiumContainerBox {
  width: 100%;
  position: relative;
  height: 83vh;
  margin: 0;
  padding: 0;

  .mapBg {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    pointer-events: none;
  }

  .layer {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 2;
    pointer-events: none;
    box-shadow: inset -200px 0px 60px -20px rgb(6 7 29 / 35%), inset 200px 0px 60px -20px rgb(6 7 29 / 35%);
  }
}

.combined-module {
  position: relative;
  width: 100%;
  height: 100%;
}

.module-switch {
  position: absolute;
  top: 1%;
  left: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
  /* 按钮之间的间距 */
}

.switch-btn {
  padding: 5px 20px;
  border: none;
  cursor: pointer;
  background: url('~@/assets/img/combined/button_choice_unselected.png') no-repeat;
  /* 未选中状态的背景图 */
  background-size: 100% 100%;
  color: #fff;
  /* 按钮文字颜色 */
  transition: all 0.3s ease;
  font-size: 14px;
}

.switch-btn.active {
  background: url('~@/assets/img/combined/button_choice_selected.png') no-repeat;
  /* 选中状态的背景图 */
  background-size: 100% 100%;
  color: #58EBFF;
}
</style>
